﻿using DrCarDrive.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DrCarDrive.DBService
{
    class ExpensesService
    {
        private DrcardriveDB db;

        public ExpensesService()
        {
            db = new DrcardriveDB();
        }

        public int save(tbl_expenses expenses)
        {
            DateTime currentDateTime = DateTime.Now;
            
            expenses.INSERT_DATE = currentDateTime;
            expenses.UPDATE_DATE = currentDateTime;

            if (expenses != null)
            {
                db.Expenses.Add(expenses);
            }
            return db.SaveChanges();
        }

        internal int update(tbl_expenses expenses)
        {
            DateTime currentDateTime = DateTime.Now;
            expenses.UPDATE_DATE = currentDateTime;

            if (expenses != null)
            {
                var original = db.Expenses.SingleOrDefault(d => d.ID.Equals(expenses.ID));
                db.Entry(original).CurrentValues.SetValues(expenses);
            }
            return db.SaveChanges();
        }

        public List<tbl_expenses> viewAll()
        {
            return db.Expenses.ToList();
        }

        public List<tbl_expense_desc> getAll()
        {
            return db.ExpenseDesc.ToList();
        }


        internal List<ExpensesView> viewByDriveID(string driveID)
        {
            var query = (from e in db.Expenses
                         where e.FKY_DRIVE == driveID
                         join ed in db.ExpenseDesc on e.FKY_EXPENSE equals ed.ID into ex
                         select new ExpensesView()
                         {
                             ExpensesDescription = ex.Select(exs => exs.DESCRIPTION).FirstOrDefault(),
                             Amount = e.AMOUNT,
                             DateTime = e.ADD_DATE,
                             Remark = e.REMARK
                         }).ToList();
            return query;
        }
    }
}
